package com.gitee.lw114514.tliasweb.controller;

import com.gitee.lw114514.tliasweb.pojo.Result;
import com.gitee.lw114514.tliasweb.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    /*
    public Result upload(String name, Integer age, MultipartFile  file) {
        log.info("上传文件:{},{},{}",name, age, file);
        //保存文件
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //生成新文件名
            String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
            //从源文件名的最后一个.开始截取
            String newFileName = UUID.randomUUID().toString() + ext;
            file.transferTo(new File("D:/test_upload/" + newFileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success();
     */
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        log.info("上传文件:{}", file);
        try {
            //将文件交给oss存储
            String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            log.info("上传成功:{}", url);
            return Result.success(url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
